<template>
    <div class="mobile-content">
        <PullRefresh v-model="refreshing" @refresh="refreshing=true;loadDetail()">
            <div class="backdrop">
                <van-image :src="detail.backdrop" width="100%" height="100%">
                    <template v-slot:loading>
                        <van-loading type="spinner" size="20" />
                    </template>
                </van-image>
            </div>
            <div class="intro">
                <div class="poster">
                    <van-image :src="detail.poster" class="img">
                        <template v-slot:loading>
                            <van-loading type="spinner" size="20" />
                        </template>
                    </van-image>
                </div>
                <div class="title">
                    <h1>{{ detail.title }}</h1>
                    <h4>{{ detail.original_title && detail.original_title != detail.title ? detail.original_title : ''}}
                    </h4>
                    <p>
                        <van-space>
                            <van-tag v-if="detail.type==='movie'" color="#87d068">电影</van-tag>
                            <van-tag v-if="detail.type==='tv'" color="#108ee9">电视剧</van-tag>
                            <van-tag type="primary">{{detail.tmdbid}}</van-tag>
                            <span>{{ detail.year }}</span>
                            <span>
                                <van-icon name="star" color="#ffd21e" />{{parseFloat(detail.score).toFixed(1)}}
                            </span>
                        </van-space>
                    </p>
                </div>
            </div>
            <div class="action-bar">
                <van-space>
                    <template v-if="detail.type==='movie'">
                        <van-button v-if="detail.subStatus==='playable'" type="success" size="small">可播放</van-button>
                        <van-button v-else-if="detail.subStatus==='sub'" type="warning" size="small">订阅中</van-button>
                        <van-button v-else-if="detail.subStatus==='find'" type="warning" size="small">已找到</van-button>
                        <van-button v-else-if="detail.subStatus==='download'" type="warning" size="small">下载中
                        </van-button>
                        <van-button v-if="!detail.subId" type="primary" size="small" icon="plus" @click="toSub">订 阅
                        </van-button>
                    </template>
                    <template v-else>
                        <van-button v-if="detail.subId && subAll" type="warning" size="small">订阅中</van-button>
                        <van-button v-else type="primary" size="small" icon="plus" @click="toSub">订 阅</van-button>
                    </template>
                    <van-button v-if="detail.subId" type="success" size="small" icon="video-o" @click="libPicker = true">
                        {{libraryName(detail.subLibraryid)}}</van-button>
                    <van-button v-if="detail.subId" type="danger" size="small" icon="guide-o" @click="subAction">更新
                    </van-button>
                    <van-button v-if="detail.subId" type="primary" size="small" icon="setting-o" @click="toSubConfig">设置
                    </van-button>
                </van-space>
            </div>
            <div class="overview">
                {{detail.overview}}
            </div>
            <div v-if="detail.credits" class="credits">
                <van-space>
                    <div v-for="(item,index) in detail.credits.cast" class="credits-card">
                        <van-image width="92" height="140"
                            :src="`${detail.credits.profile_path_base}${item.profile_path}`" />
                        <p class="credits-p1">{{item.name}}</p>
                        <p class="credits-p2">{{item.character}}</p>
                    </div>
                </van-space>
            </div>
            <div class="seasons" v-if="detail.type === 'tv'">
                <van-tabs v-model:active="active" shrink>
                    <van-tab v-for="season in detail.seasons" :title="season.name">
                        <p>{{season.overview}}</p>
                        <p>首播：{{season.air_date}}，共{{season.episode_count}}集。</p>
                        <van-cell-group>
                            <van-cell v-for="ep,index in getEpisodes(season.season_number)"
                                :title="`${index+1}.${ep.name}`" :value="ep.status" :label="ep.air_date" />
                        </van-cell-group>
                    </van-tab>
                </van-tabs>
            </div>
        </PullRefresh>



        <van-overlay :show="loading" :z-index="2">
            <div class="loading-wrapper" @click.stop>
                <van-loading></van-loading>
            </div>
        </van-overlay>
        <ActionSheet v-model:show="logsShow" title="订阅日志">
            <pre style="height: 80vh;white-space: pre-wrap;">
                {{logs}}
            </pre>
        </ActionSheet>

        <!-- 季选择器 -->
        <van-popup v-model:show="showPicker" position="bottom">
            <van-picker :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
        </van-popup>

        <!-- 媒体库选择器 -->
        <van-popup v-model:show="libPicker" position="bottom">
            <van-picker :columns="libColumns" @confirm="changeLibrary" @cancel="libPicker = false" />
        </van-popup>


        <!-- 订阅设置 -->
        <ActionSheet v-model:show="configShow" title="订阅设置">
            <SubConfig ref="subConfig" @close="() => { configShow = false; }" />
        </ActionSheet>
    </div>
</template>
  
<script name="sub-detail-mobile" setup>
import {
    Space as VanSpace, CellGroup as VanCellGroup, Cell as VanCell, Tabs as VanTabs, Tab as VanTab,
    Tag as VanTag, Button as VanButton, Overlay as VanOverlay, Loading as VanLoading, Notify,
    Popup as VanPopup, Picker as VanPicker, Image as VanImage, Icon as VanIcon, PullRefresh,
    ActionSheet
} from 'vant';
import { ref, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import SubApi from '@/api/SubApi.js';
import BaseApi from '@/api/api.js'

import SubConfig from '@/mobile/Sub/Config.vue';

import store from '@/store';

const libraryOptions = store.state.libraryOptions;
const libraryName = (libraryid) => {
    const library = libraryOptions.find(item => item.id === libraryid);
    if (library) return library.name

    return '未知媒体库';
}
const module = 'sub';

const route = useRoute()
const { tmdbid, type } = route.query;

const refreshing = ref(false);
const loading = ref(true);
const detail = ref({})
const active = ref(0);

const subAll = ref(false)
const columns = ref([])
const showPicker = ref(false)

const loadDetail = async () => {
    loading.value = true;
    SubApi.getDetail({ tmdbid, type }).then((response) => {
        if (response.data.code === 1) {
            detail.value = response.data.data;
            if (detail.value.type === 'tv') {
                columns.value = detail.value.seasons.map(season => {
                    return {
                        text: season.name,
                        value: season.season_number,
                        disabled: detail.value.subSeasons.find(ss => ss.season_number === season.season_number)
                    }
                })

                subAll.value = columns.value.every(c => c.disabled)

            }
        } else {
            Notify({ type: 'danger', message: response.data.message })
        }
    }).catch((error) => {
        Notify({ type: 'danger', message: error.message })
    }).then(() => {
        loading.value = false;
        refreshing.value = false;
    })
};

const toSub = () => {
    if (detail.value.type === 'movie') {
        doSub({
            tmdbid: detail.value.tmdbid,
            type: detail.value.type
        })
    } else if (detail.value.type === 'tv') {
        showPicker.value = true
    }
};

const onConfirm = (value) => {
    // console.log(value)
    if (value.disabled) return
    showPicker.value = false
    doSub({
        tmdbid: detail.value.tmdbid,
        type: detail.value.type,
        seasons: [value.value]
    })
}

const doSub = (form) => {
    loading.value = true
    SubApi.doSub(form).then(response => {
        if (response.data.code === 1) {
            Notify({ type: 'success', message: '订阅成功' })
            loadDetail()
        } else {
            Notify({ type: 'danger', message: response.data.message })
        }
    }).catch(error => {
        Notify({ type: 'danger', message: error.message })
    }).then(() => {
        loading.value = false
    })
}

const getEpisodes = (season_number) => {
    const subSeason = detail.value.subSeasons.find(ss => ss.season_number === season_number)
    if (subSeason) {
        subSeason.episodes.forEach(ep => {
            if (subSeason.exists && subSeason.exists.includes(ep.episode_number)) {
                ep.status = '可播放'
            } else if (subSeason.lack && subSeason.lack.includes(ep.episode_number)) {
                ep.status = '订阅中'
            } else if (subSeason.find && subSeason.find.includes(ep.episode_number)) {
                ep.status = '已找到'
            } else if (subSeason.download && subSeason.download.includes(ep.episode_number)) {
                ep.status = '下载中'
            } else {
                ep.status = '未订阅'
            }
        })
        return subSeason.episodes
    }
    return []
}

const logsShow = ref(false)
const logs = ref('')
const subAction = () => {
    if (!detail.value.subId) return;
    loading.value = true
    logs.value = ''
    SubApi.action(detail.value.subId).then(response => {
        if (response.data.code === 1) {
            logsShow.value = true
            logs.value = response.data.data
            Notify({ type: 'success', message: '操作成功' });
        } else {
            Notify({ type: 'danger', message: `操作失败：${response.data.message}` });
        }
    }).catch((error) => {
        Notify({ type: 'danger', message: `操作失败：${error.message}` });
    }).then(() => {
        loading.value = false
    })
}

const libPicker = ref(false)
const libColumns = libraryOptions.map(lib => {
    return {
        text: lib.name,
        value: lib.id,
        disabled: !lib.mediaType
    }
})
const changeLibrary = (val) => {
    if (!detail.value.subId) return;
    BaseApi.update(module, { id: detail.value.subId, libraryid: val.value }).then(response => {
        if (response.data.code === 1) {
            detail.value.subLibraryid = val.value
            Notify({ type: 'success', message: '操作成功' });
        } else {
            Notify({ type: 'danger', message: `操作失败：${response.data.message}` });
        }
    }).catch((error) => {
        Notify({ type: 'danger', message: `操作失败：${error.message}` });
    }).then(() => {
        libPicker.value = false
    })
}

// 订阅配置
const subConfig = ref(null)
const configShow = ref(false)
const toSubConfig = () => {
    configShow.value = true;
    nextTick(() => {
        subConfig.value.initModel({
            id: detail.value.subId,
        });
    })
}

loadDetail();

</script>

<style scoped>
.backdrop {
    width: 100%;
    height: 210px;
}

.intro {
    width: 100%;
    height: 120px;
    background-color: lightslategray;
    display: flex;
    color: #fff;
    margin-top: -1px;
}

.intro .poster {
    height: 100%;
    margin-left: 20px;
}

.intro .poster .img {
    width: 120px;
    height: 180px;
    object-fit: cover;
    border-radius: 10px;
    position: relative;
    top: -74px;
}

.intro .title {
    width: 100%;
    height: 100%;
    text-align: center;
}

.intro .title h1 {
    margin: .6em 0 0;
    font-size: 1.6em;
    overflow: visible;
    white-space: normal;
    color: #fff;
}

.intro .title h4 {
    margin: .5em 0;
    overflow: visible;
    white-space: normal;
    color: #fff;
}

.action-bar {
    width: 100%;
    height: 44px;
    background-color: lightslategray;
    padding-left: 48px;
}

.overview {
    width: 100%;
    padding: 12px 20px 0;
}

.credits {
    width: 100%;
    padding: 20px;
    overflow-x: auto;
}

.credits-card {
    width: 120px;
    text-align: center;
}

.credits-img {
    width: 100px;
    height: 140px;
}

.credits-p1,
.credits-p2 {
    width: 100%;
    margin-top: 0;
    margin-bottom: 0;
    overflow: hidden;
    white-space: nowrap;
}

.credits-p2 {
    font-weight: bold;
}

.seasons {
    width: 100%;
    padding: 0 20px;
}
</style>